package com.wq.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wq.common.R;
import com.wq.entity.User;
import com.wq.service.UserService;
import com.wq.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ description
 * @ author wuyunpeng
 * @ create 2022-07-23 14:47
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(HttpSession session, @RequestBody User user) {
//        获取手机号
        final String phone = user.getPhone();
        if (!StringUtils.isEmpty(phone)) {
            String code = String.valueOf(ValidateCodeUtils.generateValidateCode(4));
            log.info("收到的验证码为：{}", code);
//            session.setAttribute(phone, code);
            redisTemplate.opsForValue().set(phone, code, 5l, TimeUnit.MINUTES);
            return R.success("手机验证码短信发送成功!");
        }
        return R.error("手机验证码短信发送失败");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        log.info("map: {}", map.toString());
        /**
         * 获取前端传来的 phone 和 code
         */
        final String phone = (String) map.get("phone");
        final String code = (String) map.get(("code"));
        /**
         * 获取session中保存的自动生成的 code
         */
//        final String codeInSession = (String) session.getAttribute(phone);
        final Object codeInSession = redisTemplate.opsForValue().get(phone);
        /**
         * 对比 code 是否相同
         */
        if (codeInSession != null && code.equals(codeInSession)) {
            /**
             * 如果 User 表中没有此用户，说明是新用户，自动添加到 User 表中
             */
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone, phone);
            User user = userService.getOne(lqw);
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                userService.save(user);
            }
            session.setAttribute("user", user.getId());
//            如果用户登录成功，删除Redis中缓存的验证码
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("验证码错误,请重新输入");
    }
}
